


import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

//import wechat.rcv.generated.CallbackValidationXml;

public class WriteXMLFile {
	// final static Logger logger =
	// Logger.getLogger(FrontController.class.getName());


	public static String GenerateResonseXML(Xml res) {
		try {
			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

			// root elements
			Document doc = docBuilder.newDocument();
			Element rootElement = doc.createElement("xml");
			doc.appendChild(rootElement);

			// Encrypt elements
			Element Encrypt = doc.createElement("Encrypt");
			rootElement.appendChild(Encrypt);

			Encrypt.appendChild(doc.createTextNode(setCdataWrapper(res.getEncrypt())));

			// MsgSignature elements
			Element MsgSignature = doc.createElement("MsgSignature");
			rootElement.appendChild(MsgSignature);
			MsgSignature.appendChild(doc.createTextNode(setCdataWrapper(res.getMsgSignature())));

			// TimeStamp elements
			Element TimeStamp = doc.createElement("TimeStamp");
			rootElement.appendChild(TimeStamp);
			TimeStamp.appendChild(doc.createTextNode(setCdataWrapper(res.getTimeStamp())));

			// Nonce elements
			Element Nonce = doc.createElement("Nonce");
			rootElement.appendChild(Nonce);
			Nonce.appendChild(doc.createTextNode(setCdataWrapper(res.getNonce())));
			// // write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();

			StringWriter sw = new StringWriter();

			transformer.transform(new DOMSource(doc), new StreamResult(sw));
			return sw.toString();

		} catch (ParserConfigurationException pce) {
			pce.printStackTrace();
			return "";

		} catch (Exception ex) {
			return "";
		}

	}

	public static String setCdataWrapper(String txt) {
		return "<![CDATA[" + txt + "]]>";
	}
}
